package com.nxk.modules.core.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nxk.modules.core.entity.BaseEntity;
import com.nxk.modules.core.entity.SysParam;
import com.nxk.modules.core.entity.SysUser;
import com.nxk.modules.core.service.SysParamService;
import com.nxk.modules.core.service.SysUserService;
import com.nxk.modules.exception.ResultEntity;
import com.nxk.modules.utils.DesUtils;
import com.nxk.modules.utils.Md5utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.Subject;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/a/core/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysParamService sysParamService;

    /**
     * 保存数据接口
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @PutMapping("/save")
    public ResultEntity save(@Validated SysUser sysUser) {
        QueryWrapper<SysUser> eq = new QueryWrapper<SysUser>()
                .eq("login_code", sysUser.getLoginCode())
                .in("status", BaseEntity.STATUS_NORMAL, BaseEntity.STATUS_STOP);
        if (sysUserService.getOne(eq) == null) {
            boolean save = sysUserService.save(sysUser);
            return save ? ResultEntity.success(sysUserService.getById(sysUser.getId())) : ResultEntity.fail();
        }
        return ResultEntity.fail("此登陆账号已存在");
    }


    /**
     * 个人中心修改信息接口
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/savePersonal")
    public ResultEntity saveUser(SysUser sysUser) {
        QueryWrapper<SysUser> eq = new QueryWrapper<SysUser>()
                .eq("login_code", sysUser.getLoginCode())
                .in("status", BaseEntity.STATUS_NORMAL, BaseEntity.STATUS_STOP);
        if (sysUserService.getOne(eq) == null) {
            boolean save = sysUserService.save(sysUser);
            return save ? ResultEntity.success(sysUserService.getById(sysUser.getId())) : ResultEntity.fail();
        }
        return ResultEntity.fail("此登陆账号已存在");
    }


    /**
     * 个人中心用户修改密码接口
     */
    @PostMapping("/saveUserPassword")
    public ResultEntity saveUserPassword(String id, String originalPassword, String newPassword) {
        SysUser sysUser = new SysUser();
        //查找加密key
        SysParam sysParam = sysParamService.queryByKey("loginSecretKey");
        //解密密码
        String desOriginalPassword = DesUtils.strDec(originalPassword, sysParam.getParamValue(), null, null);
        String desNewPassword = DesUtils.strDec(newPassword, sysParam.getParamValue(), null, null);
        //判断原密码是否正确
        SysUser user = sysUserService.getUserPassWord(id);
        if (!Md5utils.encryptPassword(user.getLoginCode(), desOriginalPassword, user.getSalt()).equals(user.getPassword())) {
            return ResultEntity.fail("原密码不正确");
        }
        //保存新密码
        String salt = Md5utils.randomSalt();
        sysUser.setId(id);
        sysUser.setPassword(Md5utils.encryptPassword(user.getLoginCode(), desNewPassword, salt));
        sysUser.setSalt(salt);
        boolean flag = sysUserService.save(sysUser);
        return flag ? ResultEntity.success() : ResultEntity.fail();
    }


    /**
     * 更新数据接口
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @PostMapping("/update")
    public ResultEntity update(@Validated SysUser sysUser) {
        QueryWrapper<SysUser> eq = new QueryWrapper<SysUser>()
                .eq("login_code", sysUser.getLoginCode())
                .notIn("id", sysUser.getId())
                .in("status", BaseEntity.STATUS_NORMAL, BaseEntity.STATUS_STOP);
        if (sysUserService.getOne(eq) == null) {
            boolean save = sysUserService.save(sysUser);
            return save ? ResultEntity.success(sysUserService.getById(sysUser.getId())) : ResultEntity.fail();
        }
        return ResultEntity.fail("此登陆账号已存在");
    }


    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @PostMapping("/initPwd")
    public ResultEntity initPwd(String id) {
        boolean flag = sysUserService.initPwd(id);
        return flag ? ResultEntity.success() : ResultEntity.fail();
    }


    /**
     * 修改数据状态接口
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @PostMapping("/updateStatus")
    public ResultEntity updateStatus(SysUser sysUser) {
        SysUser user = sysUserService.getById(sysUser.getId());
        if ("system".equals(user.getUserCode())){
            ResultEntity.fail("不可修改此超级管理员信息");
        }
        boolean save = sysUserService.save(sysUser);
        return save ? ResultEntity.success(sysUserService.getById(sysUser.getId())) : ResultEntity.fail();
    }

    /**
     * 批量分配用户角色
     *
     * @param userIds
     * @param roleCode
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @PostMapping("/roleUser")
    public ResultEntity roleUser(String userIds, String roleCode) {
        String[] ids = userIds.split(",");
        List<String> list = Arrays.asList(ids);
        boolean flag = sysUserService.roleUser(list, roleCode);
        return flag ? ResultEntity.success() : ResultEntity.fail();
    }


    /**
     * 根据id获取数据接口
     *
     * @param sysUser
     * @return
     */
    @GetMapping("/get")
    public ResultEntity get(SysUser sysUser) {
        return ResultEntity.success(sysUserService.getById(sysUser.getId()));
    }

    /**
     * 查询分页数据接口
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("core:user:view")
    @PostMapping("list")
    public ResultEntity list(SysUser sysUser) {
        return ResultEntity.success(sysUserService.page(sysUser));
    }


    /**
     * 不分页查询所有正常使用的用户数据
     */
    @RequiresPermissions("core:user:view")
    @PostMapping("listAll")
    public ResultEntity listAll(SysUser sysUser) {
        return ResultEntity.success(sysUserService.listAll(sysUser));
    }

    /**
     * 根据id物理删除数据接口
     *
     * @param sysUser
     * @return
     */
    @RequiresPermissions("core:user:edit")
    @DeleteMapping("delete")
    public ResultEntity delete(SysUser sysUser) {
        boolean delete = sysUserService.deleteById(sysUser.getId());
        return delete ? ResultEntity.success() : ResultEntity.fail();
    }

}
